package com.lifeng.config;

import com.alibaba.fastjson.JSON;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * @author:lifeng
 * @date:2020/8/11 18:19
 * feign 异常处理
 */
@Configuration
public class ExceptionErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {
        try {
            if (response.body() != null) {
                Map<String,Object> exceptionMap = JSON.parseObject(Util.toString(response.body().asReader()), Map.class);
                Class clazz = Class.forName((String) exceptionMap.get("exception"));
                return (Exception) clazz.getDeclaredConstructor(String.class).newInstance(exceptionMap.get("message"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return FeignException.errorStatus(methodKey, response);
    }
}
